//
//  SelectCityViewController.m
//  JJHW_coreData
// 选择城市是公用的功能
//  Created by lizhenqiang on 16/4/9.
//  Copyright © 2016年 HFKJ_LZQ. All rights reserved.
//

#import "SelectCityViewController.h"
#import "SelectCityCollectionViewCell.h"
#import "CityObj.h"
@interface SelectCityViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@end

@implementation SelectCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    _photoCollectionView.dataSource = self;
    _photoCollectionView.delegate = self;
//    NavBarItem *rightItem = [[NavBarItem alloc] init];
//    rightItem.normalImage = [UIImage imageNamed:@"icon_dw"];
//    rightItem.selectImage = [UIImage imageNamed:@"icon_dw"];
//    rightItem.btnFrame = CGRectMake(0, 0, 30, 30);
//    rightItem.type = NavBarItemTypeImage;
//    [self setRightNavItemWith:rightItem];
    self.photoCollectionView.backgroundColor = kDefaultWhiteColor;
    [_photoCollectionView registerNib:[UINib nibWithNibName:@"SelectCityCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"SelectCityCollectionViewCell"];
    [self addLabelNoDataToView:self.view AndText:@"暂无数据" andFrame:kNoDataLabelFrame];
//    [_photoCollectionView registerNib:[UINib nibWithNibName:@"EditBuildPhotoCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EditBuildPhotoCollectionReusableView"];//UICollectionElementKindSectionHeader
    _photoArray = [NSMutableArray new];
//    for (int i=0; i<5; i++) {
//        CityObj *obj = [[CityObj alloc] init];
//        obj.name = @"北海道";
//        obj.cover = @"http://s.lifedoo.cn:8088//M00//00//07//CqgtmFcGQLSAXl9XAAEWoxwH3jo360.jpg";
//        [_photoArray addObject:obj];
//    }
    [self getCityListRequest];
    locationManager = [[CLLocationManager alloc] init];
    
    
}

-(void)rightItemClick:(id)sender
{
    //定位按钮
    
    BOOL enable=[CLLocationManager locationServicesEnabled];
    //是否具有定位权限
    int status=[CLLocationManager authorizationStatus];
    if(!enable || status<3){
        //请求权限
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示：" message:@"定位服务已被关闭，请前往设置页面打开!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"打开“定位服务”来允许“鲸鲸海外”确定您的位置" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    else
    {
        //测试用来定位 有数据的地址
        [locationManager startUpdatingLocation];
    }
    
}


- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{

    CDLog(@"定位失败");
    
}

-(void)getCityListRequest
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:_countrId,@"countryId", nil];
    //request_cityImage_WithParams
    [[CDAPIManager sharedManager] request_cityList_WithParams:dic andIsSign:YES andBlock:^(id data,NSError *error,BOOL isSuccess){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (isSuccess) {
            
            //根据他来看 是否显示 有推荐图的cell
           
            NSArray *array = [data objectForKey:@"data"];
            if (array.count>0) {
                CityObj *obj = [[CityObj alloc] init];
                obj.name = @"日本";
                obj.internalBaseClassIdentifier = @"";//城市id 为空
                obj.countryId = _countrId;//日本的国家id
                obj.cover = @"bg";
                [_photoArray addObject:obj];
            }
            for (NSDictionary *dic in array) {
                CityObj *obj = [[CityObj alloc] initWithDictionary:dic];
                [_photoArray addObject:obj];
            }
            self.labelNoData.hidden = array.count>0?YES:NO;
            [self.photoCollectionView reloadData];
        }
    
    }];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
//    self.navigationController.navigationBar.translucent = NO;//这个方法在scollview加在self.view中很重要
//    UIColor *color = NavBarBJColor;
//     [self.navigationController.navigationBar lt_setBackgroundColor:[color colorWithAlphaComponent:1.0]];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.translucent = YES;//这个方法在scollview加在self.view中很重要
//    [self.navigationController.navigationBar lt_reset];
    
    //    topBarView.hidden = YES;
    
}

#pragma mark collectionView 代理区

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   return _photoArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SelectCityCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SelectCityCollectionViewCell" forIndexPath:indexPath];
    if (indexPath.row != 0) {
        
        CityObj *obj = _photoArray[indexPath.row];
        [cell setCellData:obj];
        return cell;

    }
    else
    {
        [cell.bgImageView setImage:[UIImage imageNamed:@"bg"]];
        cell.cityNameLabel.text = @"日本";
        return cell;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (_photoArray.count>0) {
        return 1;
    }
    return 0;
}

// The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    EditBuildPhotoCollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"EditBuildPhotoCollectionReusableView" forIndexPath:indexPath];
//    if (reusableView == nil) {
//        reusableView = [[[NSBundle mainBundle] loadNibNamed:@"EditBuildPhotoCollectionReusableView" owner:self options:nil] lastObject];
//    }
//    [reusableView setcellData:_photoArray andtag:1000];
//    reusableView.isEditStatus = _isEditStatus;
//    reusableView.VC = self;
//    EditBuildPhotoObj *obj;
//    if (_photoArray.count>0) {
//        obj = _photoArray[0];
//    }
//    NSString *ImageStrUrl = [NSString stringWithFormat:@"%@%@?imageMogr2/thumbnail/!480x270r/gravity/Center/crop/%fx%f",PIC_URL,obj.pic,DeviceWidth,scaleHeight(320, 240/320)];
//    [reusableView.imageView sd_setImageWithURL:[NSURL URLWithString:ImageStrUrl] placeholderImage:[UIImage imageNamed:@"moren240"]];
//    return reusableView;
//    //    return nil;
//    
//}
/*
 - (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);
 - (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0);
 
 */


//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (DeviceWidth-25)/2;
    CGFloat height = width*(120/175.0);
    return CGSizeMake(width, height);
}
////定义每个Section 的 margin
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(0 , 10, 5, 10);//分别为上、左、下、右
//}
//返回头headerView的大小
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    
//    
//    CGSize size={DeviceWidth,DeviceWidth*3/4};
//    return size;
//}
////返回头footerView的大小
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    CGSize size={320,45};
//    return size;
//}
////每个section中不同的行之间的行间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
//{
//    return 10;
//}
//每个item之间的间距
//- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
//{
//    return 100;
//}
//选择了某个cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CityObj *obj = self.photoArray[indexPath.row];
    if (_block) {
        _block(obj);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
////取消选择了某个cell
//- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
//    [cell setBackgroundColor:[UIColor redColor]];
//}
//



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
